const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const PORT = process.env.PORT || 3000;

// 服务静态文件
app.use(express.static('public'));

// 存储所有房间信息
const rooms = new Map();

// 玩家颜色列表
const PLAYER_COLORS = ['blue', 'green', 'yellow', 'purple', 'orange'];

// 添加一个路由来显示所有房间
app.get('/rooms', (req, res) => {
    const roomList = Array.from(rooms.entries()).map(([roomId, room]) => ({
        roomId,
        playerCount: room.players.size,
        createdAt: room.createdAt,
        isFull: room.players.size >= 5  // 修改为5人上限
    }));
    res.json(roomList);
});

io.on('connection', (socket) => {
    console.log('玩家连接: ' + socket.id);

    // 处理玩家加入房间
    socket.on('joinRoom', (roomId) => {
        console.log(`玩家 ${socket.id} 尝试加入房间 ${roomId}`);

        // 如果房间不存在，创建新房间
        if (!rooms.has(roomId)) {
            rooms.set(roomId, {
                players: new Map(),
                score: new Map(),  // 每个玩家的得分
                createdAt: new Date().toISOString()
            });
            console.log(`创建新房间: ${roomId}`);
        }

        const room = rooms.get(roomId);

        // 如果房间已满，通知玩家
        if (room.players.size >= 5) {
            socket.emit('roomFull');
            console.log(`房间 ${roomId} 已满`);
            return;
        }

        // 将玩家加入房间
        socket.join(roomId);
        const playerIndex = room.players.size;
        const playerData = {
            id: socket.id,
            x: Math.random() * (800 - 40),  // 随机位置
            y: Math.random() * (600 - 40),
            health: 100,
            color: PLAYER_COLORS[playerIndex],
            direction: 'up',
            score: 0
        };
        room.players.set(socket.id, playerData);
        room.score.set(socket.id, 0);

        console.log(`玩家 ${socket.id} 成功加入房间 ${roomId}`);

        // 通知房间内所有玩家
        io.to(roomId).emit('playerJoined', {
            players: Array.from(room.players.values()),
            scores: Array.from(room.score.entries())
        });
    });

    // 处理玩家移动
    socket.on('playerMove', (data) => {
        const room = rooms.get(data.roomId);
        if (room && room.players.has(socket.id)) {
            const player = room.players.get(socket.id);
            player.x = data.x;
            player.y = data.y;
            player.direction = data.direction;

            // 广播更新给房间内所有玩家
            io.to(data.roomId).emit('gameUpdate', {
                players: Array.from(room.players.values()),
                scores: Array.from(room.score.entries())
            });
        }
    });

    // 处理玩家射击
    socket.on('playerShoot', (data) => {
        const room = rooms.get(data.roomId);
        if (room) {
            io.to(data.roomId).emit('bulletFired', {
                playerId: socket.id,
                x: data.x,
                y: data.y,
                direction: data.direction
            });
        }
    });

    // 处理击中事件
    socket.on('playerHit', (data) => {
        const room = rooms.get(data.roomId);
        if (room && room.players.has(data.targetId)) {
            const shooter = room.players.get(socket.id);
            const target = room.players.get(data.targetId);
            
            // 更新得分和生命值
            if (shooter && target) {
                target.health -= 10;
                if (target.health <= 0) {
                    room.score.set(socket.id, (room.score.get(socket.id) || 0) + 100);
                    target.health = 100;  // 重生
                    target.x = Math.random() * (800 - 40);
                    target.y = Math.random() * (600 - 40);
                }
            }

            // 广播更新
            io.to(data.roomId).emit('gameUpdate', {
                players: Array.from(room.players.values()),
                scores: Array.from(room.score.entries())
            });
        }
    });

    // 处理玩家断开连接
    socket.on('disconnect', () => {
        console.log('玩家断开连接: ' + socket.id);
        rooms.forEach((room, roomId) => {
            if (room.players.has(socket.id)) {
                room.players.delete(socket.id);
                room.score.delete(socket.id);
                io.to(roomId).emit('playerLeft', socket.id);
                
                if (room.players.size === 0) {
                    rooms.delete(roomId);
                    console.log(`房间 ${roomId} 已删除`);
                }
            }
        });
    });
});

http.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
}); 